package com.jiuqi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiuqi.entity.UserCrud;
import com.jiuqi.service.UserCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author JiuQi 玖柒
 * @Date 2021/10/31
 * @Emm...
 */
@Controller
@RequestMapping("/admin")
public class UserCrudController {

    @Autowired
    private UserCrudService userCrudService;

    @RequestMapping({"","/", "/index"})
    public String showAllUsers(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 3);
        List<UserCrud> userCruds = userCrudService.showAllUsers();
        PageInfo<UserCrud> userPageInfo = new PageInfo<>(userCruds);
        model.addAttribute("userCruds", userPageInfo);
        return "admin/index";
    }

    @GetMapping("/update")
    public String toUpdate(Model model) {
        model.addAttribute("userCruds", new UserCrud());
        return "admin/addUser";
    }

    @PostMapping("/addUser")
    public String addUser(UserCrud userCrud) {
        userCrudService.addUser(userCrud);
        return "redirect:/admin/index";
    }

    @GetMapping("/delUser/{id}")
    public String delUser(@PathVariable Integer id) {
        userCrudService.delUser(id);
        return "redirect:/admin/";
    }

    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model) {

        System.out.println("id = " + id);
        model.addAttribute("userCruds", userCrudService.selUserById(id));
        return "admin/ediUser";
    }

    @PostMapping("/edit")
    public String ediUser(UserCrud userCrud, Model model) {
        System.out.println(userCrud);
        if (userCrud.getAge() >= 1 && userCrud.getAge() <= 120) {
            userCrudService.updUser(userCrud);
        } else {
            model.addAttribute("message","年龄输入错误");
            return "admin/ediUser";
        }
        return "redirect:/admin/";
    }
}
